package servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import server.ForumAPIService;
import server.controller.WebAdapter;
import database.DBHandler;
import database.DatabaseStub;
import forum.Member;

/**
 * Servlet implementation class AddFriendServlet
 */
public class EditFriendServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditFriendServlet() {
        super();
    }
    
    @Override
    public void init(){
    	try {
			super.init();
		} catch (ServletException e) {
			System.err.println("Error in initializing register servlet!!!");
			e.printStackTrace();
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected synchronized void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();		
		ForumAPIService db = WebAdapter.getInstance();		
		String action = request.getParameter("do");	
		//System.out.println("action = "+action);
		if(action != null && action.equals("add")){			
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/editFriend.jsp");						
			dispatcher.forward(request, response);			
		}
		else 
			if (action != null && action.equals("ajaxShowFriend")){
				System.out.println("action = ajaxShowFriend");
				response.setContentType("text/xml");
				response.setHeader("Cache-Control", "no-cache");//browser won't save the results ahead
				String friendName = request.getParameter("name");
				Member friend = db.getInfoAboutFriend(friendName);
				if (friend == null){
					response.getWriter().write("User with this username does not exist!!!");
					return;
				}
				String ans = this.createStrAboutFriend(friend);
				response.getWriter().write(
						"<div align=\"left\" id=\"friend"+friendName+"\"> " + 
						"This is the information about the friend you want to add:\n"+ ans + " </div>");
				response.getWriter().flush();
				return; 	
			}
			if(action != null && action.equals("delete")){			
				String friendName = request.getParameter("name");
				if (db.removeFriend(session, friendName) == 1){
					List<Member> friends = db.getFriends(session);//(ArrayList<String>) db.removeFriend(session, friendName);	
					List<String> friendsNames = new ArrayList<String>();
					for (int i = 0; i < friends.size(); i++){
						friendsNames.add(friends.get(i).getUsername());
					}
					request.setAttribute("friends", friendsNames);
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/friendsList.jsp");						
					dispatcher.forward(request, response);
				}
			}
	}

		private String createStrAboutFriend(Member friend) {
		String ans = "";
		ans += "<p>\n";
		ans += "\n<br> <b> First Name: " + friend.getFirstName() + "</b>";
		ans += "\n <br> <b> Last Name: " + friend.getLastName() +"</b>";
		ans += "\n <br> <b> Email: " + friend.getEMail() + "</b> ";
		ans += "\n <br> <b> Gender: " + friend.getGender() + "</b>\n<br>";
		ans += "\n</p>";
		return ans;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected synchronized void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();	
		ForumAPIService db = WebAdapter.getInstance();		
		String friendName = request.getParameter("name");	
		if (db.addFriend(session, friendName) == 0){
			response.getWriter().write("Error in adding friend.\nMaybe this friend already exists in your friends' list");
		}
		else {
			response.getWriter().write("Friend was added successfully");
		}
	}
	
	@Override
	public void destroy(){
		super.destroy();
	}

}
